
import java.io.File;
import java.io.PrintWriter;

/**
 * @author Bilal Saleh
 * 
 */
public class Main {

	public static void main(String[] args) throws Exception {

		/*
		 * Verify that user has provided input file
		 */
		if (args.length < 1) {
			System.err.println("Provide input file");
			System.exit(1);
		}

		/*
		 * Input file (miny-pascal source code)
		 */
		String path = args[0];

		/*
		 * Retrieving parsing service
		 */
		parser myParser = parser.getParser(path);

		/*
		 * Retrieving the AST object
		 */
		Node root = null;
        System.out.println(myParser.getTree());

		try {
			root = myParser.getTree();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/*
		 * Extracting the input file name without extension
		 */
		int startPos = path.lastIndexOf(File.separator);
		int endPos = path.lastIndexOf(".");
		if (endPos <= startPos) {
			endPos = path.length();
		}
		String nameWithoutExtension = path.substring(0, endPos);

		/*
		 * Output AST contents (pre-order)
		 */
		String ASTFileName = nameWithoutExtension + ".ast.txt";
		PrintWriter ast_pw = new PrintWriter(ASTFileName);
		System.out.println("printing AST tree [" + ASTFileName + "]");
                if (ast_pw == null) {
                    System.out.println("ast_pw is null...");
                }
		root.translate(ast_pw, null);
		ast_pw.close();
		
		/*
		 * Output P-machine code
		 */
		String outputFileName = nameWithoutExtension + ".out";
		System.out.println("generating P-machine code [" + outputFileName + "]");
		PrintWriter out_pw = new PrintWriter(outputFileName);
		out_pw.close();

		/*
		 * End
		 */
		System.out.println("done");
	}
}
